package com.wang.tool.valve.strategy;


import com.wang.tool.util.CommonUtil;

import java.util.regex.Pattern;

/**
 * @Description 正则模型
 * @Author shaopeng
 * @Date 2021/7/21
 * @Version 1.0
 */
public class RegexValve extends AbsValve {
    private static final long serialVersionUID = 5038229758071237901L;
    /**
     * 策略名
     */
    public static final String STRATEGY = "regex";

    /**
     * 正则表达式
     * 非空
     */
    private String regex;

    /**
     * 有没有配置正则,内部属性,不序列化,如果没传正则,默认通过
     */
    private boolean noRegex;

    /**
     * 正则编译后的pattern
     * 线程安全
     */
    private Pattern compile;


    @Override
    public void prepare() throws IllegalArgumentException {
        if (CommonUtil.isBlank(regex)) {
            noRegex = true;
            return;
        }
        try {
            noRegex = false;
            compile = Pattern.compile(regex);
        } catch (Exception e) {
            throw new IllegalArgumentException("regex is not valid regex:" + regex);
        }
    }

    @Override
    protected boolean internalIsPass(Object param) {
        if (noRegex) {
            return true;
        }
        String paramStr = param == null ? "" : param.toString();
        return compile != null && compile.matcher(paramStr).matches();
    }


    public String getRegex() {
        return regex;
    }

    public void setRegex(String regex) {
        this.regex = regex;
    }

    @Override
    public String toString() {
        return "{strategy:" + STRATEGY +
                ", regex:" + regex +
                '}';
    }
}
